<?php
namespace app\mobile\controller;

use think\Request;
use think\Session;
use app\mobile\model\Member;
use app\mobile\model\MemberWithdraw;
use app\mobile\model\MemberBrokerage;

class Recharge extends BaseController
{
    // 账户充值页面
    public function index(Request $request)
    {
        // 实例化
        $member_model = new Member();
        $member_id = Session::get('member_id');

        //当前余额
        $amount = $member_model->where(['id' => $member_id])->value('balance');

        //充值订单号
        $param = "{}";
        $order_number = $this->createNumber();

        //微信配置参数 判断是否是维信内置浏览器
        if (self::is_weixin()) {
            $information = "";
            $is_weixin = 1;
        } else {
            $param = '{}';
            $information = "recharge|" . Session::get('member_id');
            $is_weixin = 2;
        }

        if ($request->has('pay_money', 'param')) {
            //微信配置参数
            $price = $request->param('pay_money');
            $param = (new Wxpay())->recharge($order_number, $price);
        }

        return $this->fetch('', [
            'information'  => $information,
            'amount'       => $amount,
            'order_number' => $order_number,
            'param'        => $param,
            'is_weixin'    => $is_weixin
        ]);
    }

    /**
     * 生成订单号码
     */
    protected function createNumber()
    {
        //订单号码主体（YYYYMMDDHHIISSNNNNNNNN）
        $order_id_main = date('YmdHis') . rand(10000000, 99999999);
        //订单号码主体长度
        $order_id_len = strlen($order_id_main);
        $order_id_sum = 0;
        for ($i = 0; $i < $order_id_len; $i++) {
            $order_id_sum += (int)(substr($order_id_main, $i, 1));
        }
        //唯一订单号码（YYYYMMDDHHIISSNNNNNNNNCC）
        $order_id = $order_id_main . str_pad((100 - $order_id_sum % 100) % 100, 2, '0', STR_PAD_LEFT);

        return $order_id;
    }


    public function is_weixin()
    {

        if (strpos($_SERVER['HTTP_USER_AGENT'],

                'MicroMessenger') !== false
        ) {

            return true;

        }

        return false;

    }

}